package com.unisci.android;

import org.json.JSONException;
import org.json.JSONObject;

import com.unisci.android.utils.HttpCmd;
import com.unisci.android.utils.HttpUtils;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class CommAsyncTask extends AsyncTask<HttpCmd, Void, HttpCmd> {

	private final String TAG = "PCR";
	private Handler mHandler;
	private boolean online = false;

	public CommAsyncTask(Handler handler) {
		mHandler = handler;
		online = false;
	}

	public void register() {
		online = true;
	}

	public void unregister() {
		online = false;
	}

	protected HttpCmd doInBackground(HttpCmd... cmd) {
		// TODO Auto-generated method stub
		HttpCmd retCmd = new HttpCmd();
		HttpCmd thisCmd = cmd[0];

		retCmd.cmd = thisCmd.cmd;
		retCmd.direction = thisCmd.direction;

		if (thisCmd.isInput()) {
			retCmd.uri = HttpUtils.get(thisCmd.uri, "utf-8");
		} else if (thisCmd.isOutput()) {
			Log.d(TAG, "do = outpiut");
			if (thisCmd.post == null) {
				Log.d(TAG, "do = outpiut isnull");
			}
			retCmd.uri = HttpUtils.post(thisCmd.uri, thisCmd.post, "utf-8");
		}
		return retCmd;
	}

	@Override
	protected void onPostExecute(HttpCmd cmd) {
		try {
			String resultString = cmd.uri;
			Log.d(TAG, "result = " + resultString);
			JSONObject json = new JSONObject(resultString);
			Message msg = new Message();
			if (json.get("status").equals("OK")) {
				msg.arg1 = HttpCmd.PCR_CMD_OK;
			} else if (json.get("status").equals("Fail")) {
				msg.arg1 = HttpCmd.PCR_CMD_FAIL;
			}
			msg.what = redirCmd(json.get("type"));
			Log.d(TAG, "type = " + msg.what);
			msg.obj = json;
			mHandler.sendMessage(msg);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private int redirCmd(Object object) {
		// TODO Auto-generated method stub
		if (object.equals("version_get")) {
			return HttpCmd.PCR_CMD_GET_VERSION;
		} else if (object.equals("runconf_get")) {
			return HttpCmd.PCR_CMD_GET_RUNCONF;
		} else if (object.equals("status_get")) {
			return HttpCmd.PCR_CMD_GET_STATUS;
		} else if (object.equals("mode_set")) {
			return HttpCmd.PCR_CMD_SET_MODE;
		} else if (object.equals("reset")) {
			return HttpCmd.PCR_CMD_RESET;
		} else if (object.equals("conf_set")) {
			return HttpCmd.PCR_CMD_SET_CONFIG;
		}

		else {
			return HttpCmd.PCR_CMD_UNKNOW;
		}
	}

}
